/**
 * 数据源设置
 */

import { mxCell } from 'mxgraph'
import DataSetting from './DataSetting'
import { useEffect, useState } from 'react'
import { Col, Divider, Row, Select } from 'antd'
import GraphUtil from '@/util/GraphUtil'
import EditorExecutor from '@/executor/EditorExecutor'
import ImageSetting from './ImageSetting'

interface IDataPaneProps {
  cells?: mxCell[]
}
export default function DataPane(props: IDataPaneProps) {
  const [cell, setCell] = useState<mxCell>()
  const [cellType, setCellType] = useState('')

  useEffect(() => {
    if (props.cells && props.cells.length > 0) {
      const c = props.cells[0]
      setCell(c)
      const name = GraphUtil.getCellAttr(c, 'type')
      setCellType(name)
    } else {
      setCell(undefined)
      setCellType('')
    }
  }, [props.cells])

  const onCellTypeChange = (v: string) => {
    const { cells } = props
    const { model } = EditorExecutor.graph
    model.beginUpdate()
    try {
      cells?.forEach((cell) => {
        let value = cell?.value
        if (!mxUtils.isNode(value, 'object')) {
          const obj = document.createElement('object')
          obj.setAttribute('label', value || '')
          value = obj.cloneNode(true)
        }
        value.setAttribute('type', v)
        cell.setValue(value)
      })
    } catch (error) {
      console.error('onCellTypeChange error')
    }
    model.endUpdate()
  }
  return (
    <>
      <Row gutter={10}>
        <Col span={8}>图元类型</Col>
        <Col span={16}>
          <Select
            options={[
              {
                label: '测点',
                value: 'HDataPoint'
              },
              {
                label: '图片',
                value: 'HImg'
              },
              {
                label: '设备',
                value: 'HDevice'
              },
              {
                label: '普通图元',
                value: ''
              }
            ]}
            value={cellType}
            className="h-26px w-100% font-size-12px"
            onChange={(v: string) => {
              onCellTypeChange(v)
            }}
          />
        </Col>
      </Row>
      <Divider className="mt-8px mb-8px" />
      {cellType != 'HImg' && <DataSetting cell={cell}></DataSetting>}
      {cellType == 'HImg' && <ImageSetting cell={cell} />}
    </>
  )
}
